import { ABP, ListService } from '@abp/ng.core';
import { Component, TrackByFunction } from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { Observable } from 'rxjs';

@Component({
  selector: '',
  template: ``,
})
export abstract class ListComponent {
  public trackByFn: TrackByFunction<AbstractControl> = (index, item) =>
    Object.keys(item)[0] || index;

  public get currentPage() {
    return this.list.page + 1;
  }

  public set currentPage(page: number) {
    this.list.page = Math.max(page - 1, 0);
  }

  public get maxResultCount() {
    return this.list.maxResultCount;
  }

  public set maxResultCount(value: number) {
    this.list.maxResultCount = value;
  }

  constructor(public readonly list: ListService<ABP.PageQueryParams>) {}

  public hookToQuery(): Promise<any> {
    return new Promise((resolve, reject) => {
      return this.list
        .hookToQuery(query => this.onQuery(query))
        .subscribe(result => {
          resolve(result);
        });
    });
  }

  protected abstract onQuery(query: ABP.PageQueryParams): Observable<any>;
}
